package request

import (
	"github.com/gin-gonic/gin"
	"strings"
)

// GetAccessToken 获取token
func GetAccessToken(c *gin.Context) string {
	token := c.Request.Header.Get(JcjHeaderKeyAccessToken)
	if token == "" {
		return ""
	}
	// 按空格分割
	parts := strings.SplitN(token, " ", 2)
	if !(len(parts) == 2 && parts[0] == "Bearer") {
		return ""
	}
	return parts[1]
}

// GetClientIP 获取客户端真实IP
func GetClientIP(ctx *gin.Context) string {

	xForwardedFor := ctx.Request.Header.Get("X-Forwarded-For") // 尝试从X-Forwarded-For头获取客户端IP
	if xForwardedFor != "" {
		ips := strings.Split(xForwardedFor, ",") // X-Forwarded-For格式: client, proxy1, proxy2, ...
		if len(ips) > 0 {
			return strings.TrimSpace(ips[0])
		}
	}

	xRealIP := ctx.Request.Header.Get("X-Real-IP") // 尝试从X-Real-IP头获取客户端IP
	if xRealIP != "" {
		return xRealIP
	}

	return ctx.ClientIP() // 最后使用RemoteAddr
}

func GetDeviceType(ctx *gin.Context) string {
	return ctx.GetHeader("device_type")
}

func GetDeviceId(ctx *gin.Context) string {
	return ctx.GetHeader("device_id")
}

func GetCurrentUser(ctx *gin.Context) string {
	return ctx.GetString(JcjHeaderKeyUUID)
}
